package com.zenithmind.exam.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.result.Result;
import com.zenithmind.exam.pojo.entity.ExamParticipant;
import com.zenithmind.exam.service.ExamParticipantService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.constraints.NotBlank;
import java.util.List;

/**
 * 考试参与者控制器
 * 
 * @author ZenithMind
 * @since 2024-07-01
 */
@Slf4j
@RestController
@RequestMapping("/api/exam/participant")
@RequiredArgsConstructor
@Validated
@Tag(name = "考试参与者管理", description = "考试参与者的相关操作")
public class ExamParticipantController {

    private final ExamParticipantService examParticipantService;

    @PostMapping("/exam/{examId}/user/{userId}")
    @Operation(summary = "添加考试参与者", description = "添加用户到考试参与者列表")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> addParticipant(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId,
            @Parameter(description = "用户ID") @PathVariable @NotBlank String userId,
            @Parameter(description = "用户姓名") @RequestParam @NotBlank String userName) {
        boolean result = examParticipantService.addParticipant(examId, userId, userName);
        return Result.success(result);
    }

    @PostMapping("/exam/{examId}/batch-add")
    @Operation(summary = "批量添加参与者", description = "批量添加用户到考试参与者列表")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> batchAddParticipants(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId,
            @Parameter(description = "用户ID列表") @RequestBody List<String> userIds) {
        boolean result = examParticipantService.batchAddParticipants(examId, userIds);
        return Result.success(result);
    }

    @DeleteMapping("/exam/{examId}/user/{userId}")
    @Operation(summary = "移除考试参与者", description = "从考试参与者列表中移除用户")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> removeParticipant(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId,
            @Parameter(description = "用户ID") @PathVariable @NotBlank String userId) {
        boolean result = examParticipantService.removeParticipant(examId, userId);
        return Result.success(result);
    }

    @PostMapping("/exam/{examId}/batch-remove")
    @Operation(summary = "批量移除参与者", description = "批量从考试参与者列表中移除用户")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> batchRemoveParticipants(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId,
            @Parameter(description = "用户ID列表") @RequestBody List<String> userIds) {
        boolean result = examParticipantService.batchRemoveParticipants(examId, userIds);
        return Result.success(result);
    }

    @PutMapping("/exam/{examId}/user/{userId}/status")
    @Operation(summary = "更新参与者状态", description = "更新考试参与者的状态")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> updateParticipantStatus(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId,
            @Parameter(description = "用户ID") @PathVariable @NotBlank String userId,
            @Parameter(description = "状态") @RequestParam Integer status) {
        boolean result = examParticipantService.updateParticipantStatus(examId, userId, status);
        return Result.success(result);
    }

    @GetMapping("/exam/{examId}")
    @Operation(summary = "获取考试参与者列表", description = "获取指定考试的参与者列表")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<List<ExamParticipant>> getParticipantsByExamId(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId) {
        List<ExamParticipant> participants = examParticipantService.getParticipantsByExamId(examId);
        return Result.success(participants);
    }

    @GetMapping("/user/{userId}")
    @Operation(summary = "获取用户参与的考试", description = "获取指定用户参与的考试列表")
    public Result<List<ExamParticipant>> getParticipantsByUserId(
            @Parameter(description = "用户ID") @PathVariable @NotBlank String userId) {
        List<ExamParticipant> participants = examParticipantService.getParticipantsByUserId(userId);
        return Result.success(participants);
    }

    @GetMapping("/my-exams")
    @Operation(summary = "获取我参与的考试", description = "获取当前用户参与的考试列表")
    @PreAuthorize("hasRole('STUDENT') or hasRole('USER') or hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<List<ExamParticipant>> getMyParticipatedExams() {
        String userId = UserContext.getUserId();
        List<ExamParticipant> participants = examParticipantService.getParticipantsByUserId(userId);
        return Result.success(participants);
    }

    @GetMapping("/exam/{examId}/page")
    @Operation(summary = "分页查询考试参与者", description = "分页查询指定考试的参与者")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<IPage<ExamParticipant>> getParticipantPage(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "用户姓名") @RequestParam(required = false) String userName,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status) {
        
        Page<ExamParticipant> page = new Page<>(pageNum, pageSize);
        IPage<ExamParticipant> result = examParticipantService.getParticipantPage(page, examId, userName, status);
        return Result.success(result);
    }

    @GetMapping("/exam/{examId}/user/{userId}/can-participate")
    @Operation(summary = "检查用户是否可以参与考试", description = "检查指定用户是否可以参与指定考试")
    public Result<Boolean> canUserParticipate(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId,
            @Parameter(description = "用户ID") @PathVariable @NotBlank String userId) {
        boolean result = examParticipantService.canUserParticipate(examId, userId);
        return Result.success(result);
    }

    @GetMapping("/exam/{examId}/count")
    @Operation(summary = "统计考试参与人数", description = "统计指定考试的参与人数")
    public Result<Integer> countParticipants(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId,
            @Parameter(description = "状态") @RequestParam(defaultValue = "1") Integer status) {
        Integer count = examParticipantService.countParticipants(examId, status);
        return Result.success(count);
    }

    @GetMapping("/exam/{examId}/user-ids")
    @Operation(summary = "获取参与者用户ID列表", description = "获取指定考试的参与者用户ID列表")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<List<String>> getParticipantUserIds(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId) {
        List<String> userIds = examParticipantService.getParticipantUserIds(examId);
        return Result.success(userIds);
    }

    @DeleteMapping("/exam/{examId}/clear")
    @Operation(summary = "清空考试参与者", description = "清空指定考试的所有参与者")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> clearParticipants(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId) {
        boolean result = examParticipantService.clearParticipants(examId);
        return Result.success(result);
    }

    @PostMapping("/exam/{examId}/import")
    @Operation(summary = "从Excel导入参与者", description = "从Excel文件导入考试参与者")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> importParticipantsFromExcel(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId,
            @Parameter(description = "文件路径") @RequestParam @NotBlank String filePath) {
        boolean result = examParticipantService.importParticipantsFromExcel(examId, filePath);
        return Result.success(result);
    }

    @GetMapping("/exam/{examId}/export")
    @Operation(summary = "导出参与者到Excel", description = "导出考试参与者到Excel文件")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<String> exportParticipantsToExcel(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId) {
        String filePath = examParticipantService.exportParticipantsToExcel(examId);
        return Result.success(filePath);
    }

    @PostMapping("/exam/{examId}/invite")
    @Operation(summary = "邀请用户参加考试", description = "邀请指定用户参加考试")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> inviteUsers(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId,
            @Parameter(description = "用户ID列表") @RequestBody List<String> userIds,
            @Parameter(description = "邀请消息") @RequestParam(required = false) String message) {
        boolean result = examParticipantService.inviteUsers(examId, userIds, message);
        return Result.success(result);
    }

    @PostMapping("/exam/{examId}/join")
    @Operation(summary = "加入考试", description = "用户主动加入考试")
    @PreAuthorize("hasRole('STUDENT') or hasRole('USER') or hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> joinExam(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId) {
        String userId = UserContext.getUserId();
        boolean result = examParticipantService.joinExam(examId, userId);
        return Result.success(result);
    }
}
